<template>
  <div class="index">
    <NavBar />
    <div class="container">
      <div class="qdet-g">
        <router-link to="/">首页</router-link>
        <i>></i>
        <router-link to="/qa">问答</router-link>
        <i>></i>正文
      </div>
      <div class="w73 qdet-l">
        <!-- 问题详情 -->
        <template v-if="detailInfo">
          <div class="item ques">
            <span class="icon icon-ques"></span>
            <h1 class="ftz18">{{detailInfo.question.questionContent}}</h1>
            <div class="tip">
              <span class="price" v-if="detailInfo.question.payment > 0">
                <span class="icon-coin"></span>{{parseFloat(detailInfo.question.payment)}}</span>
              <span class="price" v-else>免费</span>
              <span class="icon icon-def-img"></span>
              <i>{{detailInfo.creator | getUserName}}</i>
              <i> {{detailInfo.question.createTime | parseTime('{m}-{d} {h}:{i}')}}</i>
              <i>分类：{{detailInfo.question.fieldName}}</i>
              <i>阅读数：{{detailInfo.question.countRead}}</i>
              <span class="fr">
                <a href="javascript:void(0)" @click="collect(detailInfo)">
                  <i class="icon icon-collet" :class="{on: detailInfo.questionFollow === '1'}"></i>
                  <span>{{detailInfo.questionFollow === '0' ? '收藏':'取消收藏'}}</span>
                </a>
                <a href="javascript:void(0)" share>
                  <i class="icon icon-share"></i>分享</a>
              </span>
            </div>
          </div>
          <!-- 问题回答 -->
          <div class="item ans" :class="{'teacher': !detailInfo.answer && userId === detailInfo.questionedUser.userId}">
            <template v-if="detailInfo.answer && detailInfo.answer.answerContent">
              <span class="icon icon-ans"></span>
              <div class="anser-info">
                <div class="photo">
                  <router-link :to="'/dashboard/qa/' + detailInfo.questionedUser.userId">
                    <img :src="detailInfo.questionedUser.avatar" class="photo-img">
                  </router-link>
                  <img src="../../assets/res/img/icon_appr.png" class="appr">
                </div>
                <div class="anser-info-c">
                  <router-link :to="'/dashboard/qa/' + detailInfo.questionedUser.userId" class="name ftz16">{{detailInfo.questionedUser.authName}}</router-link>
                  <span class="line"></span>
                  <span>{{detailInfo.questionedUser.authOrg}}</span>
                  <p>
                    <span>擅长：{{detailInfo.questionedUser.field}}</span>
                    <span class="line h12"></span>
                    <span>回答数：{{detailInfo.questionedUser.answerCount || 0 }}</span>
                  </p>
                </div>
                <button class="fr" @click.stop.prevent="showQuestionBox(detailInfo.questionedUser)" v-if="detailInfo.questionedUser.answerPay > 0">
                  <span class="icon-coin-white"></span>{{ parseFloat(detailInfo.questionedUser.answerPay)}}</button>
                <button class="fr" @click.stop.prevent="showQuestionBox(detailInfo.questionedUser)" v-else>免费提问</button>
              </div>
              <div class="txt">{{detailInfo.answer.answerContent}}</div>
              <div class="tip">
                <span>{{detailInfo.answer.createTime | parseTime('{m}-{d} {h}:{i}')}}</span>
                <span class="fr">
                  <a href="javascript:void(0)" @click="star(detailInfo)">
                    <i class="icon icon-praise" :class="{on:detailInfo.questionStar === '1'}"></i>
                    {{detailInfo.question.countStar}}
                  </a>
                </span>
              </div>
            </template>
            <template v-else>
              <template v-if="userId === detailInfo.questionedUser.userId">
                <div class="teac-h">
                  <i class="icon icon-write"></i>
                  <span>我来回答</span>
                </div>
                <div class="teac-c" id="ans_num">
                  <textarea class="txt" placeholder="内容不少于20个字" v-model="answerContent"></textarea>
                  <button class="fr" :class="{'no': answerContent.length < 20}" type="button" @click="doSubmit()">发布</button>
                </div>
              </template>
              <template v-else>
                <span class="icon icon-ans"></span>
                <span class="no-ans">暂无回答</span>
              </template>
            </template>
          </div>
          <!-- 风险提示 -->
          <div class="risk">
            <i>风险提示：</i>【以上内容仅代表个人投资建议，不构成买卖依据，投资需谨慎！】
          </div>
        </template>
        <div class="item ques" v-if="noPermision">
          <span class="icon icon-ques"></span>
          <h1 class="ftz18">您无权查看该问题，请购买</h1>
        </div>
        <!-- 其他大咖 -->
        <div class="other">
          <div class="other-h">
            <b class="ftz16">其他大咖</b>
            <router-link to="/qa/allmasters" class="fr">更多</router-link>
          </div>
          <div class="other-c item">
            <template v-if="masterList">
              <swiper :options="swiperRecommendOption" ref="mySwiper">
                <swiper-slide v-for="(item, index) in masterList" :key="item.sysUserFieldTagVO.userId" class="swiper-item">
                  <router-link :to="'/dashboard/qa/' + item.sysUserFieldTagVO.userId">
                    <div class="photo">
                      <span><img :src="item.sysUserFieldTagVO.avatar" class="photo-img"></span>
                      <img src="../../assets/res/img/icon_appr.png" class="appr">
                    </div>
                    <b class="name ftz16">{{item.sysUserFieldTagVO.authName}}</b>
                    <div class="tips">
                      <span>擅长：{{item.sysUserFieldTagVO.field}}</span>
                      <span class="line"></span>
                      <span>回答数：{{item.sysUserFieldTagVO.answerCount ? item.sysUserFieldTagVO.answerCount : 0}}</span>
                    </div>
                    <span class="txt">
                      {{item.certification.descs}}
                    </span>
                    <div class="btn">
                      <button id="sub_btn" v-if="item.userFocus" class="black" @mouseout="showCancleBtn(item, index, false)" @mouseover="showCancleBtn(item, index, true)" @click.stop.prevent="focus(index, item)">
                        {{!item.cancleBtn ? '已关注':'取消关注'}}
                      </button>
                      <button v-else @click.stop.prevent="focus(index, item)">+关注</button>
                      <button @click.stop.prevent="showQuestionBox(item.sysUserFieldTagVO)" v-if="item.sysUserFieldTagVO.answerPay > 0">
                        <span class="icon-coin"></span>{{parseFloat(item.sysUserFieldTagVO.answerPay)}}提问</button>
                      <button @click.stop.prevent="showQuestionBox(item.sysUserFieldTagVO)" v-else>免费提问</button>
                    </div>
                  </router-link>
                </swiper-slide>
              </swiper>
              <div class="indi" id="other_indi">
                <span class="icon icon-left"></span>
                <span class="icon icon-right"></span>
              </div>
            </template>
            <NoDataTips v-else words="暂无推荐大咖" />
          </div>
        </div>
      </div>
      <div class="w23 fr qdet-r">
        <!-- 我要提问 -->
        <div class="quiz">
          <router-link to="/qa/allmasters"><img src="../../assets/res/img/quiz.png"></router-link>
        </div>
        <!-- 过去7天相似的问题 -->
        <div class="pass-ques item">
          <div class="item-h">
            <span class="line"></span>
            <b class="ftz16">过去7天相似的问题</b>
          </div>
          <div class="pass-ques-c">
            <ul v-if="similarQuestionList.length > 0">
              <li v-for="item in similarQuestionList" :key="item.question.questionId">
                <router-link :to="'/qa/' + item.question.questionId">
                  <span class="title">
                    {{item.question.questionContent}}
                  </span>
                  <div class="tip">
                    <span>{{item.question.createTime | parseTime('{m}-{d} {h}:{i}')}}</span>
                    <span class="fr">1个回答</span>
                  </div>
                </router-link>
              </li>
            </ul>
            <NoDataTips v-else />
          </div>
        </div>
      </div>
    </div>
    <!-- 提问弹窗 -->
    <transition name="fade">
      <QuestionBox v-show="questionBoxFlag" @closeFn="closeQuestionBox" @submitFn="submitQuestion" :masterInfo="targetMasterInfo" />
    </transition>
    <Footer />
  </div>
</template>

<script>
import 'swiper/dist/css/swiper.css'
import { swiper, swiperSlide } from 'vue-awesome-swiper'
import NavBar from '@/components/nav-bar'
import Footer from '@/components/footer'
import QuestionBox from '@/components/questionAnswer/question-box'
import {
  getQuestionDetail,
  answerQuestion,
  getRecommendMaster,
  getQuestionAnswerList,
  modifyUserFocus,
  starQuestion,
  followQuestion,
  unFollowQuestion
} from '@/service/api'
export default {
  components: {
    NavBar,
    Footer,
    swiper,
    swiperSlide,
    QuestionBox
  },
  mounted () {
    this.$nextTick(() => {
      this.id = this.$route.params.id
      this.showLoadingModal()
      this.initData()
    })
  },
  computed: {
    userId () {
      return this.$store.state.me.sysUser.userId
    }
  },
  filters: {
    getUserName (userInfo) {
      if (userInfo.authType === '1' || userInfo.authType === '2') {
        return userInfo.authName
      } else {
        return userInfo.userAccount
      }
    }
  },
  watch: {
    '$route' (to, val) {
      this.id = this.$route.params.id
      this.initData()
    }
  },
  data () {
    return {
      noPermision: false, // 无权查看问题
      detailInfo: null,
      answerContent: '',
      masterList: null,
      swiperRecommendOption: {
        slidesPerView: 4,
        spaceBetween: 0,
        slidesPerGroup: 4,
        loop: false,
        loopFillGroupWithBlank: true,
        navigation: {
          nextEl: '.icon-right',
          prevEl: '.icon-left'
        }
      },
      layerLoad: null,
      // 选中提问的大咖
      targetMasterInfo: {
        id: '',
        name: '',
        avatar: '',
        comment: '',
        field: '',
        answerCount: '',
        answerPay: ''
      },
      questionBoxFlag: false,
      similarQuestionList: [],
      submitting: false // 数据提交中
    }
  },
  methods: {
    showLoadingModal () {
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
    },
    closeLoadingModal () {
      if (window.layer) {
        window.layer.close(this.layerLoad)
      }
    },
    /**
     * 初始化页面数据，多个ajax同时请求
     */
    initData () {
      Promise.all([
        this.getDetailInfo()
      ]).then((res) => {
        this.noPermision = false
        this.closeLoadingModal()
        // 问题详情
        let detailData = res[0]
        if (detailData.status === 200) {
          let tempDetailData = detailData.data
          if (tempDetailData) {
            this.detailInfo = tempDetailData
            this.getRecommendMasterList() // 获取推荐大咖
            this.getSimilarQuestion() // 获取类似的问题
          } else {
            this.errorMsg('计划详情')
          }
        }
        if (window.layer) {
          window.layer.close(this.layerLoad)
        }
      }).catch((e) => {
        this.detailInfo = null
        this.noPermision = true
      })
    },
    // 问题详情
    async getDetailInfo () {
      let res = await getQuestionDetail(this.id)
      this.$nextTick(() => {
        document.title = res.data.question.questionContent + '_中亿理投师'
      })
      return res
    },
    // 推荐大咖
    async getRecommendMasterList () {
      let masterListData = await getRecommendMaster({ fieldId: this.detailInfo.question.fieldId })
      if (masterListData) {
        if (masterListData.status === 200) {
          let tempData = masterListData.data
          let list = tempData.list
          if (list) {
            let index = list.findIndex((item) => item.sysUserFieldTagVO.userId === this.detailInfo.questionedUser.userId)
            if (index >= 0) {
              list.splice(index, 1)
            }
            this.masterList = list
          }
        } else {
          this.errorMsg('推荐大咖获取失败')
        }
      }
    },
    // 类似问题
    async getSimilarQuestion () {
      let searchObj = {
        sort: '', // 最新和精彩使用该字段。  最新：'', // 精彩：'read'
        field: this.detailInfo.question.fieldId, // 其他分类问题使用该字段。
        pageSize: 5,
        pageNum: 1
      }
      let res = await getQuestionAnswerList(searchObj)
      const list = res.data.list
      if (list) {
        let index = list.findIndex((item) => item.question.questionId === this.id)
        if (index >= 0) {
          list.splice(index, 1)
        }
        this.similarQuestionList = list
      }
    },
    // 回答问题
    async doSubmit () {
      if (this.submitting) {
        this.showMsgTip('回答内容提交中……')
        return
      }
      if (this.answerContent.length < 20) {
        this.showMsgTip('回答内容不能少于20个字')
        return
      }
      this.submitting = true
      this.showLoadingModal()
      const info = {
        questionId: this.id,
        answerContent: this.answerContent,
        // nameShowable: 0,
        countStar: 0
      }
      let res = await answerQuestion(info)
      this.submitting = false
      this.closeLoadingModal()
      if (res.data) {
        window.layui.layer.msg('回答成功')
        this.detailInfo.answer = {
          answerContent: this.answerContent
        }
        this.answerContent = ''
      } else {
        window.layui.layer.msg('回答失败')
      }
    },
    showMsgTip (tip) {
      window.layui.layer.msg(tip)
    },
    // 显示提问弹窗
    showQuestionBox (item) {
      if (!this.userId) {
        this.showMsgTip('请登录后再提问！')
        return false
      }
      if (this.userId === item.userId) {
        this.showMsgTip('不能向自己提问！')
        return false
      }
      this.questionBoxFlag = true
      let answerPay = item.answerPay
      if (!answerPay) {
        answerPay = 0
      }
      this.targetMasterInfo = {
        id: item.userId,
        name: item.authName,
        avatar: item.avatar,
        comment: item.comment,
        field: item.field,
        fieldId: item.fieldId,
        answerCount: item.answerCount | 0,
        answerPay: answerPay
      }
    },
    // 关闭提问弹窗
    closeQuestionBox () {
      this.questionBoxFlag = false
    },
    // 提交问题
    submitQuestion () {
      this.questionBoxFlag = false
      console.log('ok')
    },
    showCancleBtn (item, index, flag) {
      let newItem = { ...item }
      newItem.cancleBtn = flag
      this.$set(this.masterList, index, newItem)
    },
    cancleFollowed (id) {
      console.log(id)
    },
    // 关注
    async focus (itemIndex, item) {
      if (!this.userId) {
        window.layui.layer.msg('请登录后再关注！')
        return false
      }
      let flag = item.userFocus ? '1' : '0'
      await modifyUserFocus({
        focusUserId: item.sysUserFieldTagVO.userId,
        focusStatus: flag
      })
      if (!item.userFocus) {
        item.userFocus = { focusStatus: 1 }
      } else {
        item.userFocus = null
      }
      this.$set(this.masterList, itemIndex, item)
    },
    // 收藏
    async collect (item) {
      let target = '1'
      let res = null
      if (item.questionFollow === '1') {
        target = '0'
        res = await unFollowQuestion({ questionId: item.question.questionId })
      } else {
        res = await followQuestion({ questionId: item.question.questionId })
      }
      if (res.data === null) {
        item.questionFollow = target
      }
    },
    // 点赞
    async star (item) {
      if (item.questionStar === '1') {
        return
      }
      let target = '1'
      // if (item.questionStar === '1') {
      //   target = '0'
      // }
      let res = await starQuestion({ questionId: item.question.questionId, questionStar: target })
      if (res.data === null) {
        item.questionStar = target
        if (target === '1') {
          item.question.countStar++
        }
      }
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../style/res/questiondetail.scss";
.container {
  min-height: auto;
}
</style>
